package fr.insee.solr.service.state;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

import fr.insee.solr.model.annotation.SolrField;
import fr.insee.solr.service.impl.SolrInseeException;

public class StateSimple implements IState {

	@Override
	public Object getValue(Field f, SolrField a, Object o) throws SolrInseeException {
		try {
			return PropertyUtils.getProperty(o, f.getName());
		}
		catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new SolrInseeException(ERROR_NO_SUCH_FIELD + a.fieldName(), e);
		}
	}

	@Override
	public void fillValue(Object bean, Field f, SolrField a, Object solrValue) throws SolrInseeException {
		try {
			Class<?> type = PropertyUtils.getPropertyType(bean, f.getName());
			Object value = ConvertUtils.convert(solrValue, type);
			PropertyUtils.setProperty(bean, f.getName(), value);
		}
		catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new SolrInseeException(ERROR_FILL_FIELD + a.fieldName() + " avec " + solrValue, e);
		}

	}

}
